package com.tairan.chapter.web.controller;

import com.google.common.collect.Maps;
import com.tairan.chapter.web.service.IRoleService;
import com.tairan.chapter.web.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @RequestMapping("/login")
    public ResponseEntity login(String username, String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResponseEntity.ok("登陆失败");
//            e.printStackTrace();
        }
        return ResponseEntity.ok("登陆成功");
    }

    @RequestMapping("/home")
    public ResponseEntity home() {
        Map<String, Object> body = Maps.newHashMap();
        body.put("users", userService.list());
        body.put("roles", roleService.list());
        return ResponseEntity.ok(body);
    }

    @RequestMapping("/user/update")
    public ResponseEntity userUpdate() {
        userService.createOrUpdate("");
        return ResponseEntity.ok("user更新成功");
    }

    @RequestMapping("/role/update")
    public ResponseEntity roleUpdate() {
        roleService.createOrUpdate("");
        return ResponseEntity.ok("role更新成功");
    }

    @RequestMapping("/logout")
    public ResponseEntity logout() {
        try{
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok("访问首页");
    }

    @RequestMapping("/403")
    public ResponseEntity unzuth() {
        return ResponseEntity.ok("退出成功");
    }

}
